package com.sparrow.mvc.ui;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import com.sparrow.constant.CONFIG;
import com.sparrow.utils.Config;

@SuppressWarnings("serial")
public class JScript extends TagSupport {
	private String src;

	public String getSrc() {
		return src;
	}

	public void setSrc(String src) {
		this.src = src;
	}

	@Override
	public int doStartTag() throws JspException {
		int returnValue = TagSupport.SKIP_BODY;
		String writeHTML = "";
		if (this.getSrc().contains("$language")) {
			Object language = this.pageContext.getSession().getAttribute(
					"language");
			if (language == null) {
				language = Config.getValueInCache(CONFIG.LANGUAGE);
			}
			this
					.setSrc(this.getSrc().replace("$language",
							language.toString()));
		}

		writeHTML = "<script type=\"text/javascript\"  src=\"";
		if (this.getSrc().contains("$resource")) {
			writeHTML += this.getSrc().replace("$resource",
					Config.getValueInCache(CONFIG.RESOURCE));
		} else if (this.getSrc().contains("$rootPath")) {
			writeHTML += this.getSrc().replace("$rootPath",
					Config.getValueInCache(CONFIG.ROOT_PATH));
		}

		writeHTML += "?v="
				+ Config.getValueInCache(CONFIG.RESOURCE_VERSION)
				+ "\">";

		try {
			if (!writeHTML.equals("")) {
				this.pageContext.getOut().print(writeHTML + "</script>");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return returnValue;
	}
}
